package com.mgface.zookeeper.premitive;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * 冷备切换主要实现的目的是动态创建临时节点，如果当前节点存在临时节点,就删除当前节点，再给下一个任务创建临时节点。（存在就不再重复创建）
 * 
 * @author user
 *
 */
public class 冷备切换 {
	private static Logger log = Logger.getLogger(冷备切换.class);
	private static ZooKeeper client;
	private static String path = "/Task";
	private static String task1 = path+"/task11";
	private static String task2 = path+"/task22";;
	private static boolean flags = true;
	public static void main(String[] args) throws Exception {
		CountDownLatch on = new CountDownLatch(1);
		client = new ZooKeeper("localhost:2181,localhost:2182,localhost:2183", 10_000, e -> {
			try {
				if (e.getState() == KeeperState.SyncConnected) {
					switch (e.getType()) {
					case None:
						if (e.getPath() == null) {
							on.countDown();
						}
						break;
					case NodeDeleted:
						String deleteNodeName = e.getPath();
						log.fatal("节点:" + deleteNodeName + "被删除");
						if(deleteNodeName.startsWith(task1)&&flags){
							String thread = client.create(task1 + "/thread", "thread".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
							List<String> nodes = client.getChildren(task1, false);
							Collections.sort(nodes);//进行自然排序，按照最小节点优先算法
							if(nodes.size()>1&&!thread.equals(nodes.get(0))){
								client.delete(thread, -1);
							}else{
								flags = false;
							}
							log.fatal("《监控task1》生成节点:"+thread+"值:"+new String(client.getData(thread, false, null)));
						}
						if(deleteNodeName.startsWith(task2)&&flags){
							String thread2 = client.create(task2 + "/thread2", "thread2".getBytes(), Ids.OPEN_ACL_UNSAFE,
									CreateMode.EPHEMERAL_SEQUENTIAL);
							log.fatal(thread2);
							List<String> task2s = client.getChildren(task2, false);
							Collections.sort(task2s);// 进行自然排序，按照最小节点优先算法
							if (task2s.size() > 1 && !thread2.equals(task2s.get(0))) {
								client.delete(thread2, -1);
							}else{
								flags = false;
							}
							log.fatal("《监控task2》生成节点:"+thread2+"值:"+new String(client.getData(thread2, false, null)));
						}
						break;
					default:
						break;
					}
				}
			} catch (Exception error) {
				error.getMessage();
			}

		});
		log.fatal("ZK状态:" + client.getState().toString());
		on.await();
		log.fatal("zookeeper session 建立完成");
		Stat stat = client.exists(path, false);
		if (stat == null) {
			client.create(path, "task".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		}
		Stat stat1 = client.exists(path + "/task11", false);
		if (stat1 == null) {
			task1 = client.create(path + "/task11", "task11".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
			log.fatal(task1);
		}
		Stat stat2 = client.exists(path + "/task22", false);
		if (stat2 == null) {
			task2 = client.create(path + "/task22", "task22".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
			log.fatal(task2);
		}
		
		String thread = client.create(task1 + "/thread", "thread".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
		log.fatal(thread);
		
		List<String> nodes = client.getChildren(task1, false);
		boolean flag = false;//设置标示，如果创建不成功就接着创建.
		Collections.sort(nodes);//进行自然排序，按照最小节点优先算法
		if(nodes.size()>1&&!thread.equals(nodes.get(0))){
			client.exists(task1+"/"+nodes.get(0), true);
			log.fatal("删除节点:"+thread+"值:"+new String(client.getData(thread, false, null)));
			client.delete(thread, -1);
			flag = true;
		}
		if (flag) {
			flag = false;
			String thread2 = client.create(task2 + "/thread2", "thread2".getBytes(), Ids.OPEN_ACL_UNSAFE,
					CreateMode.EPHEMERAL_SEQUENTIAL);
			log.fatal(thread2);
			List<String> task2s = client.getChildren(task2, false);
			Collections.sort(task2s);// 进行自然排序，按照最小节点优先算法
			if (task2s.size() > 1 && !thread2.equals(task2s.get(0))) {
				client.exists(task2+"/"+task2s.get(0), true);
				log.fatal("删除节点:"+thread2+"值:"+new String(client.getData(thread2, false, null)));
				client.delete(thread2, -1);
				flag = true;
			}
		}
//		log.fatal("当前节点:"+newpath+",值:"+new String(client.getData(newpath, false, null)));
		TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
	}
}
